package com.lexis.wallpaper;

import com.lexis.wallpaper.sheregesh.R;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class BitmapManager {
	private static final String TAG = BitmapManager.class.getSimpleName();
	private static Bitmap sBitmap;
	
//	private static Bitmap decodeOriginalBitmap(Resources resources) {
//        BitmapFactory.Options opts = new BitmapFactory.Options();
//        opts.inScaled = false;
//        return BitmapFactory.decodeResource(resources, R.raw.image, opts);
//	}
	
	public static Bitmap newBitmap(Resources resources, int desiredWidth, int desiredHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inScaled = false;
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, R.raw.image, opts);
        
        int bmpHeight = opts.outHeight;
        int bmpWidth = opts.outWidth;

        float wFactor = (float)desiredWidth / bmpWidth;
        float hFactor = (float)desiredHeight / bmpHeight;
        float factor = (hFactor > wFactor) ? hFactor : wFactor;
        int decodeSample = (int)(1/factor);
        
        Log.d(TAG, "onSurfaceChanged - initial bitmap: " + bmpWidth + "," + bmpHeight + "; scale factor: " + factor);

        BitmapFactory.Options decodeOpts = new BitmapFactory.Options();
        decodeOpts.inSampleSize = decodeSample;
        decodeOpts.inScaled = false;
        
        Log.d(TAG, "onSurfaceChanged - bitmap sample size: " + decodeSample);
        
        Bitmap bitmap = BitmapFactory.decodeResource(resources, R.raw.image, decodeOpts);
        
        bmpHeight = bitmap.getHeight();
        bmpWidth = bitmap.getWidth();

        Log.d(TAG, "onSurfaceChanged - decoded bitmap: " + bmpWidth + "x" + bmpHeight);

        wFactor = (float)desiredWidth / bmpWidth;
        hFactor = (float)desiredHeight / bmpHeight;
        factor = (hFactor > wFactor) ? hFactor : wFactor;
        
        sBitmap = Bitmap.createScaledBitmap(bitmap, (int)(bmpWidth*factor), (int)(bmpHeight*factor), false);
                    
        Log.d(TAG, "onSurfaceChanged - scaled bitmap: " + sBitmap.getWidth() + "," + sBitmap.getHeight());
        
        return sBitmap;
	}
	
	public static Bitmap getBitmap(Resources resources, int desiredWidth, int desiredHeight, boolean exactSize) {
		if ((sBitmap == null) || (exactSize && desiredHeight != sBitmap.getHeight()) || (desiredWidth > sBitmap.getWidth())) {
			return newBitmap(resources, desiredWidth, desiredHeight);			
		} else {
			return sBitmap;
		}
	}
}
